from fastapi import Request
from typing import List
from starlette.responses import StreamingResponse
import asyncio


class SSEManager:
    def __init__(self):
        self.clients: List[asyncio.Queue] = []

    async def publish(self, data: str):
        for client in self.clients:
            await client.put(data)

    async def subscribe(self, request: Request):
        client_queue = asyncio.Queue()
        self.clients.append(client_queue)

        async def event_stream():
            while True:
                if await request.is_disconnected():
                    self.clients.remove(client_queue)
                    break

                data = await client_queue.get()
                print(data)
                yield f"data: {data}\n\n"

        return StreamingResponse(event_stream(), media_type="text/event-stream")
